package com.xplan.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * json 工具类
 * 
 * @author will
 * 
 */
@SuppressWarnings("unchecked")
public class JsonHelper {

	private static String MapToJson(Map map) {
		String json = "";
		Iterator it = map.keySet().iterator();
		while (it.hasNext()) {
			Object key = it.next();
			json += "\"" + key.toString() + "\":";
			Object value = map.get(key);

			if (value instanceof java.util.List) {
				json += JsonHelper.ListToJson((List) value)+",";
			} else {
				json += "\"" + value.toString() + "\",";
			}
		}
		json=json.length()>0?json.substring(0,json.length()-1):"";
		return json;
	}

	private static String ListToJson(List<Map> list) {
		String json = "";
		for (Map map : list) {
			json+="{";
			json+= JsonHelper.MapToJson(map) + "},";
		}
		json = json.length() > 0 ? json.substring(0, json.length() - 1) : "";
		json="["+json;

		return json+"]";
	}

	/**
	 * 转换json字符串
	 * 
	 * @param obj
	 *            仅限为 List 、Map
	 * @return
	 */
	public static String toJson(Object obj) {

		String json = "";
		if (obj instanceof java.util.List) {
			json+= JsonHelper.ListToJson((List) obj);
		} else if (obj instanceof java.util.Map) {
			json+="{";
			json+= JsonHelper.MapToJson((Map) obj);
			json+="}";
		} 
		return json;
	}
	
	
	
	public static void main(String [] args){
		List list=new ArrayList();
		Map map=new HashMap();
		map.put("name","will");
		map.put("age", 20);
//		list.add(map);
//		list.add(map);
		
	
		System.out.println(JsonHelper.toJson(list));
		
	}

}
